<template>
  <div class="app-container">
     <el-form :model="queryParam" ref="queryForm" size="small" :inline="true"  >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="queryParam.roleName"
              placeholder="请输入角色名称"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleKey">
            <el-input
              v-model="queryParam.roleKey"
              placeholder="请输入权限字符"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParam.status"
              placeholder="角色状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dicts.sys_normal_disable"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="createTimeValue"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="btnSearch">搜索</el-button>
          </el-form-item>
        </el-form>

     <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd()"
              v-hasPerm="['system:role:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPerm="['system:role:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPerm="['system:role:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport()"
              v-hasPerm="['system:role:export']"
            >导出</el-button>
          </el-col>
        </el-row>

       <el-table v-loading="loading" :data="tableData.rows" @selection-change="handleSelectionChange">
             <el-table-column type="selection" width="55" align="center" />
             <el-table-column label="角色编号" prop="roleId" width="120" />
             <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
             <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
             <el-table-column label="显示顺序" prop="roleSort" width="100" />
             <el-table-column label="状态" align="center" width="180">
               <template slot-scope="scope">
                 <el-switch
                   v-model="scope.row.status"
                   active-value="0"
                   :active-text="scope.row.status==='0'?'正常':''"
                   inactive-value="1"
                   :inactive-text="scope.row.status==='1'?'停用':''"
                   :disabled="scope.row.roleId === 1"
                   @change="handleStatusChange(scope.row)"
                 ></el-switch>
               </template>
             </el-table-column>
             <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
             <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
               <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                 <el-button
                   size="mini"
                   type="text"
                   icon="el-icon-view"
                   @click="handleView(scope.row)"
                   v-hasPerm="['system:role:query']"
                 >详情</el-button>
                 <el-button
                   size="mini"
                   type="text"
                   icon="el-icon-edit"
                   @click="handleUpdate(scope.row)"
                   v-hasPerm="['system:role:edit']"
                 >修改</el-button>
                 <el-button
                   size="mini"
                   type="text"
                   icon="el-icon-delete"
                   @click="handleDelete(scope.row)"
                   v-hasPerm="['system:role:remove']"
                 >删除</el-button>
               </template>
             </el-table-column>
           </el-table>

        <el-pagination v-if="tableData.total>0" :current-page="queryParam.page" :page-sizes="[10, 20,30,50]"
          :page-size="queryParam.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />

       <!-- 添加或修改角色配置对话框 -->
          <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :before-close="cancelForm" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入角色名称" />
              </el-form-item>
              <el-form-item prop="roleKey">
               <span slot="label">
                 <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                   <i class="el-icon-question"></i>
                 </el-tooltip>
                 权限字符
               </span>
                <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
              </el-form-item>
              <el-form-item label="角色顺序" prop="roleSort">
                <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dicts.sys_normal_disable"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="菜单权限">
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
                <el-tree
                  class="tree-border"
                  :data="menuOptions"
                  show-checkbox
                  ref="menu"
                  node-key="id"
                  :check-strictly="!menuCheckStrictly"
                  empty-text="加载中，请稍候"
                  :props="defaultProps"
                ></el-tree>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancelForm">取 消</el-button>
            </div>
          </el-dialog>


          <!-- 显示详情-->
          <el-dialog :title="detailTitle" :visible.sync="openDetail" width="800px" append-to-body>
            <el-form ref="form" :model="formDetail"  label-width="100px">
              <el-form-item label="角色名称" prop="roleName">
                {{formDetail.roleName}}
              </el-form-item>
              <el-form-item label="角色权限"  prop="roleKey">
                {{formDetail.roleKey}}
              </el-form-item>
              <el-form-item label="角色顺序" prop="roleSort">
                {{formDetail.roleSort}}
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="formDetail.status">
                  <el-radio
                     v-for="dict in dicts.sys_normal_disable"
                     :key="dict.dictValue"
                     :label="dict.dictValue"
                   >{{dict.dictLabel}}</el-radio>
                 </el-radio-group>
              </el-form-item>
              <el-form-item label="菜单权限">
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menuDetail')">展开/折叠</el-checkbox>
                <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menuDetail')">全选/全不选</el-checkbox>
                <el-tree
                  class="tree-border"
                  :data="menuOptions"
                  show-checkbox
                  ref="menuDetail"
                  node-key="id"
                  :check-strictly="!menuCheckStrictly"
                  empty-text="加载中，请稍候"
                  :props="defaultProps"
                ></el-tree>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="openDetail=false">取 消</el-button>
            </div>

          </el-dialog>

  </div>
</template>

<script>
  import {dataListApi, addApi, editApi,deleteApi, findByIdApi,checkRoleNameUnique, checkRoleKeyUnique} from '@/api/role.js'
  import { treeselect as menuTreeselect, roleMenuTreeselect } from '@/api/menu'
  import PageMinix from '@/mixin/PageMixin.js'
  import AddOrEditMixin from '@/mixin/AddOrEditMixin.js'
  import DictDataMinix from '@/mixin/DictDataMinix.js'
  export default {
    mixins: [DictDataMinix, PageMinix, AddOrEditMixin],
    dicts: ['sys_normal_disable'],
    data() {

      return {
        fetchDataApi: dataListApi,
        addApi: addApi,
        editApi: editApi,
        deleteByIdApi: deleteApi,
        findByIdApi: findByIdApi,
        primaryKey: 'roleId',
        // 菜单树型节点父子联动
        menuCheckStrictly: true,
        // 所有菜单列表
        menuOptions: [],
        // 菜单全部折叠
        menuExpand: false,
        // 菜单全选
        menuNodeAll: false,
        // 菜单列表属性
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
           roleName: [
            {required: true, message: "不能为空", trigger: "blur"}
          ],
          roleKey: [
            {required: true, message: "不能为空", trigger: "blur"}
          ],
          roleSort: [
            {required: true, message: "不能为空", trigger: "blur"}
          ]
        }
      }
    },
    methods: {
     initFormValue() {
       this.form = {
         status: '0',
         roleSort: 0,
         menuIds: []
       }
     //  清空所有的菜单选项
       if (this.$refs.menu) {
         this.$refs.menu.setCheckedKeys([])
       }
       // 折叠
         this.menuExpand = false
         // 全部不要选中
         this.menuNodeAll = false

     },
     handleStatusChange(row) {
     //  超级管理员任何人都不能更改
       if (row[this.primaryKey] == 1) {
         row.status = '0'
         return
       }
       this.$confirm('确定改状态吗','提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }).then(() => {
         changeRoleStatus(row[this.primaryKey], row.status).then(resp => {
           this.$message('操作成功');
           this.fetchData()
         }).catch(() => {
           row.status = row.status==='1'? '0' : '1'
         })
       }).catch(() => {
         row.status = row.status==='1'? '0' : '1'
       })
     },
     // 导出excel
     handleExport(){
       this.download('api/role/export', {
             ...this.queryParam
           }, `role_${new Date().getTime()}.xlsx`)
     },
      // 树权限(父子联动)
     handleCheckedTreeConnect(value, type) {
       if (type == 'menu') {
         this.$refs.menu.menuCheckStrictly = value ? true : false
       }else if(type === 'menuDetail') {
         this.$refs.menuDetail.menuCheckStrictly = value ? true : false
       }
     },
     // 展开折叠
     handleCheckedTreeExpand(value, type) {
         //  菜单的展开/ 折叠
          if (type === 'menu') {
            for (let i = 0; i<this.$refs.menu.store._getAllNodes().length; i++){
              this.$refs.menu.store._getAllNodes()[i].expanded = value
            }
          }else if(type === 'menuDetail') {
            for (let i = 0; i<this.$refs.menuDetail.store._getAllNodes().length; i++){
              this.$refs.menuDetail.store._getAllNodes()[i].expanded = value
            }
          }
     },
     // 全选全不选
     handleCheckedTreeNodeAll(value, type) {
         if (type == 'menu') {
           this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
         }else if(type === 'menuDetail') {
           this.$refs.menuDetail.setCheckedNodes(value ? this.menuOptions : [])
         }
     },
     fetchMenuTree(){
       // 查询所有的菜单列表
        menuTreeselect().then(resp => {
          this.menuOptions = resp.data
        })
     },
     // 点击新增按钮之前要做的事情
     preAddHandler() {
       this.fetchMenuTree()
     },
      // 新增保存之前的操作
     preAddSaveHandler() {
       this.form.menuIds = this.getMenuAllCheckedKeys()
     },
     // 获取当前选中的菜单节点数据
     getMenuAllCheckedKeys() {
     //  目前被选中的菜单节点
       let checkedKeys = this.$refs.menu.getCheckedKeys()
     //  半选中的菜单节点
       let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
     //  合并两个数组
       checkedKeys.unshift.apply(checkedKeys,halfCheckedKeys)
       return checkedKeys
     },
     // 点击显示详情之前做的事情
     preViewHandler(roleId){
       // 树型不要父子联动
        this.menuCheckStrictly = false
       //   查询该角色的菜单权限
         roleMenuTreeselect(roleId).then(resp => {
           this.menuOptions = resp.data.menus
           const checkedKeys= resp.data.checkedKeys
           // 循环遍历拥有的角色，并且赋值给前端
           this.$refs.menuDetail.setCheckedKeys(checkedKeys)
           // 树型要父子联动
           this.menuCheckStrictly = true
         })
     },
      // 点击修改要做的事情
      preEditHandler(roleId) {
        // 树型不要父子联动
        this.menuCheckStrictly = false
       //   查询该角色的菜单权限
         roleMenuTreeselect(roleId).then(resp => {
           this.menuOptions = resp.data.menus
           const checkedKeys= resp.data.checkedKeys
           // 循环遍历拥有的角色，并且赋值给前端
           this.$refs.menu.setCheckedKeys(checkedKeys)

           // 树型要父子联动
           this.menuCheckStrictly = true
         })

       },
       // 修改保存之前要做的事情
       preEditSaveHandler(){
         this.form.menuIds = this.getMenuAllCheckedKeys()
       }

    },
    created(){
      this.initFormValue()
    }
  }
</script>

<style>
</style>
